package br.ufrj.neg.reuniao.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.velocity.tools.view.VelocityViewServlet;

import br.ufrj.neg.constants.General;
import br.ufrj.neg.reuniao.bean.ArtefatoBean;
import br.ufrj.neg.reuniao.bean.ReuniaoBean;

public class DownloadArtefatoReuniaoAction extends VelocityViewServlet {

	private static final long serialVersionUID = 1L;

	// private static Logger log = Logger.getLogger("rootLogger");

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		ReuniaoBean rb = null;
		try {
			HttpSession session = request.getSession(false);
			synchronized (session) {
				rb = (ReuniaoBean) session.getAttribute("ReuniaoBean");
			}
			/*
			 * Pega os parametros passados
			 */
			String indArtefato = request.getParameter("indArtefato");
			ArtefatoBean ab = rb.getArtefatos().get(
					Integer.valueOf(indArtefato));

			if( ab.getTipoArtefato() == 1 ){
				response.setContentType("application/pdf");
			}
			else if(ab.getTipoArtefato() == 2 ){
				response.setContentType("application/doc");
			}
			else if(ab.getTipoArtefato() == 3 ){
				response.setContentType("application/ppt");
			}
			else if(ab.getTipoArtefato() == 4 ){
				response.setContentType("application/xsl");
			}
			else if(ab.getTipoArtefato() == 5 ){
				response.setContentType("application/project");
			}
			else if(ab.getTipoArtefato() == 6 ){
				response.setContentType("image/jpg");
			}		
			else{
				response.setContentType("application/octet-stream");
			}
			
			
			response.setHeader("Content-Disposition", "attachment;filename="
					+ ab.getNome());

			// OutputStream os
			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentLength(ab.getArquivoAsByte().length);
			outputStream.write(ab.getArquivoAsByte());
			outputStream.flush();
			outputStream.close();

		} catch (Exception e) {
			System.out.println(e);
			request.getRequestDispatcher(General.TELA_ERRO_500).forward(request,
					response);
		}
	}

}
